package com.tsfyun.scm.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.tsfyun.common.base.config.OrikaBeanMapper;
import com.tsfyun.common.base.constant.CacheConstant;
import com.tsfyun.common.base.exception.ServiceException;
import com.tsfyun.common.base.extension.OrderItem;
import com.tsfyun.scm.system.dto.UnitDTO;
import com.tsfyun.scm.system.entity.Unit;
import com.tsfyun.scm.system.mapper.UnitMapper;
import com.tsfyun.scm.system.service.IUnitService;
import com.tsfyun.common.base.extension.ServiceImpl;
import com.tsfyun.scm.system.util.TsfWeekendSqls;
import com.tsfyun.scm.system.vo.UnitVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *

 * @since 2020-03-19
 */
@Slf4j
@Service
public class UnitServiceImpl extends ServiceImpl<Unit> implements IUnitService {

    @Autowired
    private OrikaBeanMapper beanMapper;

    @Override
    public PageInfo<Unit> list(UnitDTO dto) {
        TsfWeekendSqls sqls = TsfWeekendSqls.<Unit>custom().andLike(true,Unit::getName,dto.getName());
        return super.pageList(dto.getPage(),dto.getLimit(),sqls, Lists.newArrayList(OrderItem.desc("sort")));
    }

    @Override
    public UnitVO detail(String id) {
        Unit unit = super.getById(id);
        Optional.ofNullable(unit).orElseThrow(()->new ServiceException("单位不存在"));
        return beanMapper.map(unit,UnitVO.class);
    }

    @Cacheable(value = CacheConstant.UNIT_LIST,key = "'select'")
    @Override
    public List<UnitVO> select() {
        Unit condition = new Unit();
        List<Unit> list = super.list(condition);
        if(CollectionUtil.isNotEmpty(list)) {
            list = list.stream().sorted(Comparator.comparing(Unit::getSort).reversed()).collect(Collectors.toList());
            return beanMapper.mapAsList(list,UnitVO.class);
        }
        return Lists.newArrayList();
    }

    @CacheEvict(value = CacheConstant.UNIT_LIST,allEntries = true,beforeInvocation = true)
    @Override
    public void clear() {
        log.info("清除单位缓存成功");
    }
}
